package com.jishi.gouwuche.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.jishi.gouwuche.common.Result;
import com.jishi.gouwuche.dao.Commodity;
import com.jishi.gouwuche.dao.ShoppingCart;
import com.jishi.gouwuche.dao.User;
import com.jishi.gouwuche.entity.CommodityDto;
import com.jishi.gouwuche.entity.ShoppingCartDto;
import com.jishi.gouwuche.entity.UserDto;
import com.jishi.gouwuche.entity.Zhifu;
import com.jishi.gouwuche.service.CommodityService;
import com.jishi.gouwuche.service.ShoppingCartService;
import com.jishi.gouwuche.service.UserService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

@RestController
public class Api {
    @Resource
    private UserService userService;
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private CommodityService commodityService;

    //登录
    @PostMapping("/login")
    public Result adduser(String username, String password, boolean rememberMe) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        System.out.println(rememberMe);//rememberMe为true则shiro会帮我们记住用户的登录状态
        System.out.println(Thread.currentThread().getName());
        try {
            subject.login(token);
            User user = (User) subject.getPrincipal();
            subject.getSession().setAttribute("user", user);
            user.setUpdateTime(new Date());
            userService.updateById(user);
            return Result.success("登录成功");
        } catch (UnknownAccountException e) {
            return Result.error("账号不存在");
        } catch (LockedAccountException e) {
            return Result.error("账号被锁定");
        } catch (DisabledAccountException e) {
            return Result.error("账号被禁用");
        }
    }

    @GetMapping("/unauth")
    public Result unauth() {
        return Result.error("未授权，无法访问！");
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.error("退出成功");
    }
    //注册
    @PostMapping("/zhuce")
    public Result zc(@RequestBody UserDto ud) {
        try {
            Validator.validateNotEmpty(ud.getName(), "用户名不能为空");
            Validator.validateNotEmpty(ud.getUname(), "账号不能为空");
            Validator.validateNotEmpty(ud.getPwd(), "密码不能为空");
            Validator.validateNotEmpty(ud.getMobile(), "手机号不能为空");
            Validator.validateMobile(ud.getMobile(), "手机号格式错误");
            User u = userService.getByName(ud.getUname());
            if (u != null) {
                throw new Exception("账号已存在");
            }
            User user = new User();
            user.setUsername(ud.getUname());
            user.setPassword(DigestUtil.md5Hex(ud.getPwd()));
            user.setName(ud.getName());
            user.setPhone(ud.getMobile());
            user.setCreateTime(new Date());
            if (userService.save(user)) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    //获取商品信息
    @GetMapping("/list_commodity")
    public Result getList(){
        List<Commodity> list=commodityService.list();
        List<CommodityDto> rlist=list.stream().map(v-> CommodityDto.builder()
                .id(v.getId())
                .name(v.getName())
                .jsId(v.getUserId())
                .jq(v.getPrice())
                .tu(v.getIcon())
                .gs(v.getQuantity())
                .build()
        ).toList();
        return Result.success(rlist);
    }
    //获取购物车信息
    @GetMapping("/list_shoppingCart")
    public Result getShoppingCart(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        LambdaQueryWrapper<ShoppingCart> lw=new LambdaQueryWrapper<>();
        lw.eq(ShoppingCart::getUserId,user.getId());
        List<ShoppingCart> list=shoppingCartService.list(lw);
        List<ShoppingCartDto> rlist=list.stream().map(v-> ShoppingCartDto.builder()
                .id(v.getId())
                .name(v.getName())
                .jsId(v.getUserId())
                .qian(v.getPrice())
                .tu(v.getIcon())
                .spId(v.getCommodityId())
                .shuliang(v.getAmount())
                .build()
        ).toList();
        return Result.success(rlist);
    }

    //添加商品到购物车
    @PostMapping("/add_shoppingCart")
    public Result addShoppingCart(@RequestBody CommodityDto sp){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        LambdaQueryWrapper<ShoppingCart> lw=new LambdaQueryWrapper<>();
        lw.eq(ShoppingCart::getUserId,user.getId())
                .eq(ShoppingCart::getName,sp.getName());
        List<ShoppingCart> s= shoppingCartService.list(lw);
        System.out.println(s);
        if ( s.isEmpty()){
        ShoppingCart gwc=new ShoppingCart();
        gwc.setCommodityId(sp.getId());
        gwc.setName(sp.getName());
        gwc.setIcon(sp.getTu());
        gwc.setPrice(sp.getJq());
        gwc.setUserId(user.getId());
        if (shoppingCartService.save(gwc)){
            return Result.success(null);
        }else{
            return Result.error("添加失败");
        }
    }
        return  Result.error("购物车已存在此商品");
    }
    //添加商品
    @PostMapping("/add_commodity")
    public Result addCommodity(@RequestBody CommodityDto sp){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Commodity cc=new Commodity();
        cc.setName(sp.getName());
        cc.setIcon(sp.getTu());
        cc.setPrice(sp.getJq());
        cc.setQuantity(sp.getGs());
        cc.setType(sp.getLeixing());
        cc.setUserId(user.getId());
        if (commodityService.save(cc)){
            return Result.success(null);
        }else{
            return Result.error("添加失败");
        }
    }

    //获取当前登录信息
    @GetMapping("/list_user")
    public Result ListUser(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        LambdaQueryWrapper<User> lw=new LambdaQueryWrapper<>();
        lw.eq(User::getId,user.getId());
        List<User> list=userService.list(lw);
        List<UserDto> rlist=list.stream().map(v-> UserDto.builder()
                .id(v.getId())
                .name(v.getName())
                .qianbao(v.getPurse())
                .build()
        ).toList();
        return Result.success(rlist);
    }
    //修改购物车商品个数
    @PutMapping("/update_shoppingCart/{id}/{g}")
    public Result updateShopping(@PathVariable Integer id,@PathVariable int g){
        System.out.println(id);
        System.out.println(g);
        LambdaUpdateWrapper<ShoppingCart> lw =new LambdaUpdateWrapper<>();
        lw.eq(ShoppingCart::getId,id).set(ShoppingCart::getAmount,g);
        shoppingCartService.update(lw);
        return Result.success(null);
    }
    //删除购物
    @DeleteMapping("/remove_shoppingCart/{id}")
    public Result removeShopping(@PathVariable Integer id){
        if (shoppingCartService.removeById(id)){
            return Result.success(null);
        }
        return Result.error("删除失败");
    }

    //模糊查询
    @GetMapping("/listLike_commodity/{xx}")
    public Result XcCommodity(@PathVariable String xx){
        LambdaQueryWrapper<Commodity> lw=new LambdaQueryWrapper<>();
        lw.like(Commodity::getName,xx);
        List<Commodity> list=commodityService.list(lw);
        List<CommodityDto> rlist=list.stream().map(v-> CommodityDto.builder()
                .id(v.getId())
                .name(v.getName())
                .jsId(v.getUserId())
                .jq(v.getPrice())
                .tu(v.getIcon())
                .gs(v.getQuantity())
                .build()
        ).toList();
        return Result.success(rlist);
    }

    //支付修改
    @PutMapping("/update_shoppingUser")
    public Result upShoppingUser(@RequestBody Zhifu zf){
        AtomicInteger ss= new AtomicInteger();
        AtomicReference<Double> jq= new AtomicReference<>((double) 0);
        LambdaQueryWrapper<Commodity> ll=new LambdaQueryWrapper<>();
        ll.eq(Commodity::getId,zf.getSpid());
        List<Commodity> list= commodityService.list(ll);
        list.forEach(i->
                ss.set(i.getQuantity() - zf.getSl())
        );
        System.out.println(ss);
//        LambdaUpdateWrapper<Commodity> lw=new LambdaUpdateWrapper<>();
//        lw.eq(Commodity::getId,zf.getSpid()).set(Commodity::getQuantity,ss);
//        commodityService.update(lw);

        return Result.success(null);
    }

}
